using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Blog.IService;
using Blog.Command;
using Blog.Model;
using Microsoft.AspNetCore.Authorization;

namespace Blog.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class TypeControllers : ControllerBase
    {
        private readonly ITypeInfoService _iTypeInfoService;

        public TypeControllers(ITypeInfoService iTypeInfoService)
        {
            _iTypeInfoService = iTypeInfoService;
        }

        [HttpGet]
        public async Task<ApiResult> QueryAsync()
        {
            var types = await _iTypeInfoService.QueryAsync();
            if (types.Count == 0)
                return ApiResultHelper.Error("没有更多的类型");
            return ApiResultHelper.Success(types);
        }

        [HttpPost]
        public async Task<ApiResult> CreateAsync(string name)
        {
            if(string.IsNullOrWhiteSpace(name))
                return ApiResultHelper.Error("文章类型名称不能为空");
            TypeInfo typeInfos = new()
            {
                Name = name,
            };
            bool bl = await _iTypeInfoService.CreateAsync(typeInfos);
            if (!bl)
                return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(typeInfos);
        }

        [HttpPut]
        public async Task<ApiResult> EditAsync(int id, string name)
        {
            var typeinfos = await _iTypeInfoService.FindAsync(id);
            if (typeinfos == null)
                return ApiResultHelper.Error("没有找到文章类型");
            typeinfos.Name = name;
            bool bl = await _iTypeInfoService.EditAsync(typeinfos);
            if (!bl)
                return ApiResultHelper.Error("更新数据失败");
            return ApiResultHelper.Success(typeinfos);
        }

        [HttpDelete]
        public async Task<ApiResult> DeleteAsync(int id)
        {
            bool bl = await _iTypeInfoService.DeleteAsync(id);
            if (!bl)
                return ApiResultHelper.Error("删除失败");
            return ApiResultHelper.Success(bl);
        }
        
    }
}